#!/bin/bash
set -o pipefail;

#TODO:activate when ready
# remove these comments and the exit statement; for now fail it
#exit 1

PGNAME=`basename $0`
PGDIRNAME=`dirname $0`
PGERR="$PGNAME[$$]: "
PGUSER=`id -un`


if [ "${MLPROD_HOME}" == "" ]
then
  echo "${PGERR} :  MLPROD_HOME env not set;  exiting !!!" >&2
  exit 10
fi

PGCFG_FILE="${MLPROD_HOME}/config/mlprog.rc"
if [ ! -f ${PGCFG_FILE} ]
then
  echo "${PGERR} : config file <${PGCFG_FILE}> not found; exiting !!!" >&2
  exit 10
fi

. "${PGCFG_FILE}"

CUST_CTX="$(mlget_cust_ctx 'cust')"
MOD_CTX="$(mlget_cust_ctx  'mod')"
BATCH_WFL_ID=1                  # workflow/product id
BATCH_MODE="oper"
if [ ! -z ${BATCH_RUN_MODE} ]
then
  BATCH_MODE="${BATCH_RUN_MODE}"
fi
LOG_CTX="${BATCH_MODE}-${CUST_CTX}"


PGCFG_FILE="${MLPROD_HOME}/cust/${CUST_CTX}/config/${MOD_CTX}.rc"
if [ ! -f ${PGCFG_FILE} ]
then
  echo "${PGERR} : config file <${PGCFG_FILE}> not found; exiting !!!" >&2
  exit 10
fi

. "${PGCFG_FILE}"
if [ ! -f ${PGCFG_FILE} ]
then
  echo "${PGERR} : config file sourcing <${PGCFG_FILE}> error; exiting !!!" >&2
  exit 10
fi


function cleanup
{
  rm -f ${EDER_DSTATUS_FILE};
  rm -f ${EDER_ESTATUS_FILE};

  if [ -f ${OUT_INSURANCE_FILE} ]
  then
    rm -f ${OUT_INSURANCE_FILE}
    if [ $? -ne 0 ]
    then
      mllogerr "[${LOG_CTX}] : ERR : Unable to cleanup files : ${OUT_INSURANCE_FILE}";
    fi
  fi

}

trap cleanup EXIT ERR TERM INT QUIT

function usage()
{
  mllogerr "Usage: $PGNAME -p PART -b MMDDYY_HHMMSS_XXXXXX WHERE XXXXXX is cust_id";
}

if [ $# -ne 4 ]
then
  usage;
  exit 10;
fi


PART=-1
DBATE="";
while getopts "p:b:" opts
do
  case $opts in
    b ) BPARAMETER=$OPTARG
	;;
    p ) PART=$OPTARG
        ;;
    * ) usage; exit 10;
        ;;
  esac
done

if [ -z ${BPARAMETER} ]
then
  usage
  exit 10
fi


# LOG
LOG_CTX="${LOG_CTX}-${BPARAMETER}"


# OVERWRITE THE ARCHIVE DIRECTORIES to archive/recon/in AND archive/recon/backup
ARCH_CTX_IN_DIR="${MLARCH_DIR}/recon/in"
ARCH_CTX_BAK_DIR="${MLARCH_DIR}/recon/backup"

# RECON FILE
IN_RECON_FILE=${ARCH_CTX_IN_DIR}/${BPARAMETER}.recon

# BACKUP FILES 
RECON_BAK_FILE=${ARCH_CTX_BAK_DIR}/${BPARAMETER}_recon_t.txt
BATCH_STATUS_BAK_FILE=${ARCH_CTX_BAK_DIR}/${BPARAMETER}_batch_status_recon_t.txt


if [ ! -d ${LOG_CTX_DIR} ]
then
  mkdir -p ${LOG_CTX_DIR}
  if [ $? -ne 0 ]
  then
    mllogerr "[${LOG_CTX}] : ERR : Unable to create log folder : ${LOG_CTX_DIR}";
    exit 10;
  fi
fi

if [ ! -r ${IN_RECON_FILE} ]
then
  mllogerr "[${LOG_CTX}] : ERR : Recon File Not Found : ${IN_RECON_FILE}";
  exit 10;
fi


tstart=$((`date +%s`))

tstamp="00:00:00"
mllogerr "[${LOG_CTX}] : BEG : [${tstamp}] : BATCH START"



################################################################################################################
# SELECTION PROCESSING                                                                                         #
# IS THIS                                                                                                      #
# AN EXCEL SPREADSHEET FROM CLIENT                                                                             #
# B) A FILE FROM INSURANCE2 PROCESS (TEXT FILE STARTING WITH "M")                                              #
# C) AN UPDATE FILE FROM VALIDATION PROCESS (TEXT FILE STARTING WITH "U"                                       #
# D) A TRIGGER FILE TO SEND A RECON FILE TO CLIENT (TEXT FILE STARTING WITH "C"                                #
################################################################################################################

TTEST=`file ${IN_RECON_FILE} | grep 'ASCII' `
if [ "${TTEST}" = "" ]; then
   TTEST="C"                              # Excell spreadsheet containing recon information from client or populated by Tony
else
   TTEST=`head -c 2 ${IN_RECON_FILE}`
   if [ "${TTEST}" = "R|" ]; then         # a trigger file to output recon report
     TTEST="R"
   elif [ "${TTEST}" = "M|" ]; then       #output from insurance2_results to be loaded
     TTEST="M"
   elif [ "${TTEST}" = "C|" ]; then       #file created from transaction data
     TTEST="T"
   elif [ "${TTEST}" = "U|" -o "${TTEST}" = "E|" ]; then       #result of the validation process or edit on our web page
     TTEST="U"
   else
     TTEST=""
   fi
fi


## REFRESHING SQL CODE

TASK_ID=`expr $TASK_ID + 1`
tmsg="load sql modules";
mllogerr "[${LOG_CTX}] : INF : TASK-${TASK_ID} $tmsg";
ts=$((`date +%s`))
${SQL_CTX_CMN_RUNT_DIR}/load_funcs.sh
if [ $? -ne 0 ]
then
  mllogerr "[${LOG_CTX}] : ERR : TASK-${TASK_ID} failed to ${tmsg}";
  cleanup;
  exit 1$TASK_ID;
fi
te=$((`date +%s`))

ts=$((`date +%s`))
${SQL_CTX_RUNT_DIR}/load_funcs.sh
if [ $? -ne 0 ]
then
  mllogerr "[${LOG_CTX}] : ERR : TASK-${TASK_ID} failed to ${tmsg}";
  cleanup;
  exit 1$TASK_ID;
fi
te=$((`date +%s`))



## LOADING PHASE

case "${TTEST}" in
        C)
                TASK_ID=`expr $TASK_ID + 1`
                tmsg="loading temp batch recon table";
                mllogerr "[${LOG_CTX}] : INF : TASK-${TASK_ID} $tmsg";
                ts=$((`date +%s`))
                ${PGDIRNAME}/../common/read_spreadsheet.pl ${IN_RECON_FILE} \
                | ${PGDIRNAME}/../common/convert_xlsx.pl \
                | ${PGSQL} ${SQL_CTX_RUNT_DIR}/load_table_batch_temp_recon.sql
                if [ $? -ne 0 ]
                then
                        mllogerr "[${LOG_CTX}] : ERR : TASK-${TASK_ID} failed to ${tmsg}";
                        cleanup;
                        exit 1$TASK_ID;
                fi
                te=$((`date +%s`))
          ;;
        T)
                TASK_ID=`expr $TASK_ID + 1`
                tmsg="loading temp batch recon table";
                mllogerr "[${LOG_CTX}] : INF : TASK-${TASK_ID} $tmsg";
                ts=$((`date +%s`))
                cat ${IN_RECON_FILE} | ${PGDIRNAME}/../common/convert_xlsx.pl \
                | ${PGSQL} ${SQL_CTX_RUNT_DIR}/load_table_batch_temp_recon.sql
                if [ $? -ne 0 ]
                then
                        mllogerr "[${LOG_CTX}] : ERR : TASK-${TASK_ID} failed to ${tmsg}";
                        cleanup;
                        exit 1$TASK_ID;
                fi
                te=$((`date +%s`))
          ;;
        M|U|R)
                TASK_ID=`expr $TASK_ID + 1`
                tmsg="loading temp batch recon table";
                mllogerr "[${LOG_CTX}] : INF : TASK-${TASK_ID} $tmsg";
                ts=$((`date +%s`))
                cat ${IN_RECON_FILE} | ${PGSQL} ${SQL_CTX_RUNT_DIR}/load_table_batch_temp_recon.sql
                if [ $? -ne 0 ]
                then
                        mllogerr "[${LOG_CTX}] : ERR : TASK-${TASK_ID} failed to ${tmsg}";
                        cleanup;
                        exit 1$TASK_ID;
                fi
                te=$((`date +%s`))
          ;;
        *)
           mllogerr "[${LOG_CTX}] : ERR : RECON FILE IN UNKNOWN FORMAT"
           cleanup;
           exit 100;
          ;;
esac



# PROCESSING AND BACKING-UP PHASE 

case "${TTEST}" in
        M|C|U|R|T)

		TASK_ID=`expr $TASK_ID + 1`
		tmsg="audit recon table";
		mllogerr "[${LOG_CTX}] : INF : TASK-${TASK_ID} $tmsg";
		ts=$((`date +%s`))
		${PGSQL} ${SQL_CTX_RUNT_DIR}/audit_tables_recon.sql
		if [ $? -ne 0 ]
		then
  			mllogerr "[${LOG_CTX}] : ERR : TASK-${TASK_ID} failed to ${tmsg}";
  			cleanup;
  			exit -1;      # recon module will be put offline
		fi
		te=$((`date +%s`))


                TASK_ID=`expr $TASK_ID + 1`
                tmsg="load into batch_recon_t";
                mllogerr "[${LOG_CTX}] : INF : TASK-${TASK_ID} $tmsg";
                ts=$((`date +%s`))
                ${PGSQL} ${SQL_CTX_RUNT_DIR}/load_table_batch_recon.sql
                if [ $? -ne 0 ]
                then
                        mllogerr "[${LOG_CTX}] : ERR : TASK-${TASK_ID} failed to ${tmsg}";
                        cleanup;
                	exit -1;
                fi
                te=$((`date +%s`))


                TASK_ID=`expr $TASK_ID + 1`
                tmsg="load into recon_t";
                mllogerr "[${LOG_CTX}] : INF : TASK-${TASK_ID} $tmsg";
                ts=$((`date +%s`))
                ${PGSQL} ${SQL_CTX_RUNT_DIR}/load_table_recon.sql
                if [ $? -ne 0 ]
                then
                        mllogerr "[${LOG_CTX}] : ERR : TASK-${TASK_ID} failed to ${tmsg}";
                        cleanup;
                	exit -1;
                fi
                te=$((`date +%s`))


		# update batch status recon done
		${PGSQL} ${SQL_CTX_RUNT_DIR}/create_funcs_batch_status_recon.sql
		if [ $? -ne 0 ]
		then
  			mllogerr "[${LOG_CTX}] : ERR : Batch status recon done update failed"
  			cleanup;
  			exit -1;
		fi

                TASK_ID=`expr $TASK_ID + 1`
                tmsg="backup recon_t table";
                mllogerr "[${LOG_CTX}] : INF : TASK-${TASK_ID} $tmsg";
                ts=$((`date +%s`))
                ${PGSQL} ${SQL_CTX_BAK_DIR}/copy_table_recon.sql > ${RECON_BAK_FILE}
                if [ $? -ne 0 ]
                then
                        mllogerr "[${LOG_CTX}] : ERR : TASK-${TASK_ID} failed to ${tmsg}";
                        cleanup;
                        exit -1;
                fi
                te=$((`date +%s`))


                TASK_ID=`expr $TASK_ID + 1`
                tmsg="backup batch_status_recon";
                mllogerr "[${LOG_CTX}] : INF : TASK-${TASK_ID} $tmsg";
                ts=$((`date +%s`))
                ${PGSQL} ${SQL_CTX_BAK_DIR}/copy_table_batch_status_recon.sql > ${BATCH_STATUS_BAK_FILE}
                if [ $? -ne 0 ]
                then
                        mllogerr "[${LOG_CTX}] : ERR : TASK-${TASK_ID} failed to ${tmsg}";
                        cleanup;
                        exit -1;
                fi
                te=$((`date +%s`))

                # BACKUP TABLES WHICH ARE NOT batch BASED
		TASK_ID=`expr $TASK_ID + 1`
		tmsg="backup recon_userid_t table";
		mllogerr "[${LOG_CTX}] : INF : TASK-${TASK_ID} $tmsg";
		ts=$((`date +%s`))
                ${PGSQL} ${SQL_CTX_BAK_DIR}/copy_table_recon_userid.sql >  ${SQL_CTX_SETUP_DIR}/dbdata/recon_userid_t.data
		if [ $? -ne 0 ]
		then
  		  mllogerr "[${LOG_CTX}] : ERR : TASK-${TASK_ID} failed to ${tmsg}";
  		  cleanup;
  		  exit -1;
		fi
		te=$((`date +%s`))

                TASK_ID=`expr $TASK_ID + 1`
                tmsg="backup recon_admin_t table";
                mllogerr "[${LOG_CTX}] : INF : TASK-${TASK_ID} $tmsg";
                ts=$((`date +%s`))
                ${PGSQL} ${SQL_CTX_BAK_DIR}/copy_table_recon_admin.sql >  ${SQL_CTX_SETUP_DIR}/dbdata/recon_admin_t.data
                if [ $? -ne 0 ]
                then
                  mllogerr "[${LOG_CTX}] : ERR : TASK-${TASK_ID} failed to ${tmsg}";
                  cleanup;
                  exit -1;
                fi
                te=$((`date +%s`))

                TASK_ID=`expr $TASK_ID + 1`
                tmsg="backup recon_filemap_t table";
                mllogerr "[${LOG_CTX}] : INF : TASK-${TASK_ID} $tmsg";
                ts=$((`date +%s`))
                ${PGSQL} ${SQL_CTX_BAK_DIR}/copy_table_recon_filemap.sql >  ${SQL_CTX_SETUP_DIR}/dbdata/recon_filemap_t.data
                if [ $? -ne 0 ]
                then
                  mllogerr "[${LOG_CTX}] : ERR : TASK-${TASK_ID} failed to ${tmsg}";
                  cleanup;
                  exit -1;
                fi
                te=$((`date +%s`))

                TASK_ID=`expr $TASK_ID + 1`
                tmsg="backup invoices_t table";
                mllogerr "[${LOG_CTX}] : INF : TASK-${TASK_ID} $tmsg";
                ts=$((`date +%s`))
                ${PGSQL} ${SQL_CTX_BAK_DIR}/copy_table_invoices_t.sql >  ${SQL_CTX_SETUP_DIR}/dbdata/invoices_t.data
                if [ $? -ne 0 ]
                then
                  mllogerr "[${LOG_CTX}] : ERR : TASK-${TASK_ID} failed to ${tmsg}";
                  cleanup;
                  exit -1;
                fi
                te=$((`date +%s`))

                TASK_ID=`expr $TASK_ID + 1`
                tmsg="backup insurance_type_t table";
                mllogerr "[${LOG_CTX}] : INF : TASK-${TASK_ID} $tmsg";
                ts=$((`date +%s`))
                ${PGSQL} ${SQL_CTX_BAK_DIR}/copy_table_insurance_type_t.sql >  ${SQL_CTX_SETUP_DIR}/dbdata/insurance_type_t.data
                if [ $? -ne 0 ]
                then
                  mllogerr "[${LOG_CTX}] : ERR : TASK-${TASK_ID} failed to ${tmsg}";
                  cleanup;
                  exit -1;
                fi
                te=$((`date +%s`))

                TASK_ID=`expr $TASK_ID + 1`
                tmsg="backup customer_billing_t table";
                mllogerr "[${LOG_CTX}] : INF : TASK-${TASK_ID} $tmsg";
                ts=$((`date +%s`))
                ${PGSQL} ${SQL_CTX_BAK_DIR}/copy_table_customer_billing_t.sql >  ${SQL_CTX_SETUP_DIR}/dbdata/customer_billing_t.data
                if [ $? -ne 0 ]
                then
                  mllogerr "[${LOG_CTX}] : ERR : TASK-${TASK_ID} failed to ${tmsg}";
                  cleanup;
                  exit -1;
                fi
                te=$((`date +%s`))


          ;;
esac



# EXPORT REPORT PHASE 

case "${TTEST}" in
        R)
                TASK_ID=`expr $TASK_ID + 1`
                tmsg="create recon excel spreadsheet";
                mllogerr "[${LOG_CTX}] : INF : TASK-${TASK_ID} $tmsg";
                ts=$((`date +%s`))
                ${PGDIRNAME}/../common/recon_report.pl -b ${BPARAMETER} 
                if [ $? -ne 0 ]
                then
                        mllogerr "[${LOG_CTX}] : ERR : TASK-${TASK_ID} failed to ${tmsg}";
                        cleanup;
                        exit -1;
                fi
                te=$((`date +%s`))

          ;;
esac


tstamp="$(mltstamp ${tstart})"
mllogerr "[${LOG_CTX}] : END : [${tstamp}] : BATCH DONE"

exit 0;
